package edu.lingnan.blog.gateway.handler;


import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import edu.lingnan.blog.common.core.utils.ServletUtils;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * 自定义限流异常处理
 *
 * @author cql
 */
public class SentinelFallbackHandler implements WebExceptionHandler {

    private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange, String msg) {
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg);
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {

        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }
        if (!BlockException.isBlockException(ex)) {
            return Mono.error(ex);
        }
        String msg;
        // 触发限流
        if (ex instanceof FlowException) {
            msg = "触发限流";
        }
        // 授权规则不通过
        else if (ex instanceof AuthorityException) {
            msg = "授权规则不通过";
        }
        // 服务降级
        else if (ex instanceof DegradeException) {
            msg = "服务降级";
        }
        // 热点参数限流
        else if (ex instanceof ParamFlowException) {
            msg = "触发热点限流";
        }
        // 系统保护
        else if (ex instanceof SystemBlockException) {
            msg = "触发系统保护规则";
        }
        // 兜底
        else {
            msg = "内部服务器错误";
        }
        String finalMsg = msg;
        return handleBlockedRequest(exchange, ex).flatMap(response -> writeResponse(response, exchange, finalMsg));
    }

    private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {
        return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
    }
}
